var app = getApp()
var util = require('../../../utils/util.js');
var netWork = require('../../../utils/netutil.js');
var config = require('../../../utils/config.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // listArray: new Array(),
    currentDate: '',
    goDate: '',
    goWeek: '',
    backDate: '',
    backWeek: '',
    vcType: '',//当前viewController类型，去程或是返程.
    priceIsUp: false,//是否是价格从高到低，默认按数据下发顺序
    timeIsUp: false,//时间
    sortSelect: 0,//默认选择0，
    fromCity: null,
    toCity: null,
    SerFee: 0,//服务费
    totalMoney: 0,//总价
    trainStandard: new Object(),//差标信息(TravelStandard)
    isShowAlert: false,//是否显示差标alert(超标)
    standardReason: '',//差标继续预定原因（超标）
    flightInfo: null,
    cabinInfo: null,
    isShowAlertLess: false,//低价提醒提示alert
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.data.vcType = options.vcType;

    that.data.goDate = options.goDate;
    that.data.goWeek = options.goWeek;
    that.data.fromCity = JSON.parse(options.fromCity);
    that.data.toCity = JSON.parse(options.toCity);


    wx.setNavigationBarTitle({
      title: that.data.fromCity.CityName + '-' + that.data.toCity.CityName,
    })
    that.loadData(that.data.goDate);

    //获取差标信息
    that.getTravelStandard();
    wx.setNavigationBarTitle({
      title: that.data.fromCity.CityName + '-' + that.data.toCity.CityName,
    })
    //set the data
    that.setData({
      goDate: that.data.goDate,
      goWeek: that.data.goWeek,
    })
    console.log('date：' + that.data.goDate);
  },


  //prepare the Date string.
  prepareDateStr: function (theDate) {
    var dateStr = theDate + ' ' + util.getTheDateWeek(theDate);
    return dateStr;
  },

  //load the main data
  loadData: function (dateStr) {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    console.log('list Loading...');

    var postData = that.preparePostDic(dateStr);
    var url = config.getBaseUrl('FlightApi', 'FlightQuery');
    netWork.post(
      url,
      postData,
      function (res) {//success
        console.log(res.data);
        if (res.data.ResponseMetaInfo.StatusCode == '0') {//成功
          var listArray = res.data.Data.Flights;
          if(listArray == null) {
            wx.hideLoading();
            //刷新列表
            that.setData({
              listArray: [],
            })
            return;
          }
          console.log('服务费' + res.data.Data.SerFee);
          that.data.SerFee = res.data.Data.SerFee;

          //添加cell展开折叠控制字段
          for (var i = 0; i < listArray.length; i++) {
            listArray[i].cellSelect = 'N';
          }
          wx.hideLoading()
          

          wx.setNavigationBarTitle({
            title: that.data.fromCity.CityName + '-' + that.data.toCity.CityName + '(' + listArray.length + ')',
          })
          //刷新列表
          that.setData({
            listArray: listArray,
          })
        }else {
          wx.hideLoading()
          wx.showToast({
            title: res.data.ResponseMetaInfo.Reason,
          })
        }
      },

      function (res) {//fail
        wx.hideLoading()
      }
    )
  },
  //创建请求列表数据所需的postDic
  preparePostDic: function (dateStr) {
    var that = this;
    var postDic = new Object();
    postDic.SiteID = app.globalData.TUserInfo.SiteID;//站点ID
    postDic.EID = app.globalData.TUserInfo.EID;//企业ID(必填 计算返佣时需要)
    postDic.StartCode = that.data.fromCity.CityCode;////起飞城市三字码
    postDic.EndCode = that.data.toCity.CityCode;////到达城市三字码
    postDic.TakeOffDate = dateStr;//起飞日期 "2017-08-22",
    console.log('国内机票list参数');
    console.log(postDic);
    return postDic;
  },
  /**
 * 查询差标信息
 */
  getTravelStandard: function () {
    var that = this;
    var postData = new Object();
    postData.UserID = app.globalData.TUserInfo.UserID
    var url = config.getBaseUrl('CommonApi', 'GetTravelStandard');
    netWork.post(
      url,
      postData,
      function (res) {//success
        console.log('差标.');
        console.log(res.data);
        if (res.data.ResponseMetaInfo.StatusCode == '0') {
          //未配置会返回null
          var travelStandard = res.data.Data.TravelStandard;
          if (travelStandard != null) {
            console.log('trainLimit');
            console.log(travelStandard);
            that.data.trainStandard = travelStandard;
          }
        }
        else {

        }
      },
      function (res) {//fail
      }
    )
  },
  //show request loading..
  showLoading: function () {
    wx.showLoading({
      title: '加载中...',
    })
  },
  //cell上折叠开关
  openOrClose: function (res) {
    var that = this;
    var index = res.currentTarget.dataset.index;
    console.log('cell:' + index);

    var status = that.data.listArray[index].cellSelect;
    if (status == 'N') {
      that.data.listArray[index].cellSelect = 'Y';
    } else {
      that.data.listArray[index].cellSelect = 'N';
    }

    that.setData({
      listArray: that.data.listArray
    })
  },
  //订购按钮tap
  orderTap: function (res) {
    var that = this;
    var cellindex = res.currentTarget.dataset.cellindex;
    var index = res.currentTarget.dataset.index;
    console.log('cellindex:' + cellindex + 'moreIndex:' + index);
  },
  //headerV_前一天
  theDayBefore: function () {
    var that = this;
    var dateStr = that.data.goDate;
    var theDayBefore = util.getTheDayBeforeDate(dateStr, true);
    var weekStr = util.getTheDateWeek(theDayBefore);

    that.setData({
      goDate: theDayBefore,
      goWeek: weekStr,
    })
    console.log('before');
    //load new data
    that.loadData(theDayBefore);
    
  },
  //headerV_后一天
  theDayAfter: function () {
    console.log('after');
    var that = this;
    var dateStr = that.data.goDate;
    var theDayAfter = util.getTheDayBeforeDate(dateStr, false);
    var weekStr = util.getTheDateWeek(theDayAfter);

    that.setData({
      goDate: theDayAfter,
      goWeek: weekStr,
    })
    //load new data
    that.loadData(theDayAfter);
  },
  //headerV_选择日期
  selectDateTap: function () {
    var that = this;
    wx.navigateTo({//type：0-火车票，1-国内机票
      url: '../../dateSelect/dateSelect?startDate=' + that.data.goDate + '&isStartDate=' + 1 + '&type=' + 1
    })
  },

  //价格排序(默认从低到高)
  priceSort: function () {
    console.log('priceSort');
    var that = this;
    that.data.priceIsUp = !that.data.priceIsUp;

    that.sortThePriceByFare(that.data.priceIsUp);
  },

  //时间排序(默认从早到晚)
  timeSort: function () {
    console.log('timeSort');
    var that = this;
    that.data.timeIsUp = !that.data.timeIsUp;
    that.sortTheTimeByOffTime(that.data.timeIsUp);
  },

  ///价格排序抽取方法,isUp为true，从低到高
  sortThePriceByFare: function (isUp) {
    var that = this;
    var listArray = that.data.listArray;
    var temp = null;
    for (var i = 0; i < listArray.length - 1; i++) {
      for (var j = 0; j < listArray.length - 1 - i; j++) {
        var a = listArray[j].MinFare;
        var b = listArray[j + 1].MinFare;
        if (isUp) {
          if (a > b) {
            temp = listArray[j + 1];
            listArray[j + 1] = listArray[j];
            listArray[j] = temp;
          }
        }
        else {
          if (a < b) {
            temp = listArray[j + 1];
            listArray[j + 1] = listArray[j];
            listArray[j] = temp;
          }
        }
      }
    }

    that.setData({
      listArray: listArray,
      priceIsUp: isUp,
      sortSelect: 1,
    })
  },

  ///时间排序抽取方法，
  sortTheTimeByOffTime: function (isUp) {
    var that = this;
    var listArray = that.data.listArray;
    var temp = null;
    for (var i = 0; i < listArray.length - 1; i++) {
      for (var j = 0; j < listArray.length - 1 - i; j++) {
        var a = listArray[j].OffTime;
        var b = listArray[j + 1].OffTime;
        if (isUp) {
          if (a > b) {
            temp = listArray[j + 1];
            listArray[j + 1] = listArray[j];
            listArray[j] = temp;
          }
        }
        else {
          if (a < b) {
            temp = listArray[j + 1];
            listArray[j + 1] = listArray[j];
            listArray[j] = temp;
          }
        }
      }
    }

    that.setData({
      listArray: listArray,
      timeIsUp: isUp,
      sortSelect: 2,

    })
  },
  //callBack选择日期回调函数--
  updateTicketStartDate: function (dateStr, weekStr) {
    var that = this;
    that.setData({
      goDate: dateStr,
      goWeek: weekStr,
    })
    console.log('日期回调。。。。。。。');
    //load new data

    that.loadData(dateStr);
  },
  //关闭超标提醒
  closeAlertView: function () {
    var that = this;
    that.setData({
      isShowAlert: false,
    })
  },
  //关闭最低价提醒
  closeAlertLess: function () {
    var that = this;
    that.setData({
      isShowAlertLess: false,
    })
  },
  //继续预定_超标
  continueOrder: function () {
    var that = this;
    if (that.data.standardReason.length == 0) {
      wx.showToast({
        title: '请填写原因',
      })
      return;
    } else {
      that.jumpToOrderVc(that.data.flightInfo, that.data.cabinInfo, that.data.standardReason, true, 2);
    }
  },
  //超标继续预定原因
  resonInput: function (res) {
    var that = this;
    that.data.standardReason = res.detail.value;
  },
  //低价提醒，原因选择
  selectItem: function (res) {
    var that = this;
    var item = res.currentTarget.dataset.item;
    console.log(item);
    that.setData({
      item: item,
    })
  },
  //继续预定该航班_低价提醒
  continueOrderTheFlight: function () {
    var that = this;
    if (that.data.item == null) {//没有选择原因
      wx.showToast({
        title: '请选择原因',
      })
    } else {
      var reasonArr = [
        '机型，线路，航班周期不可接受',
        '起飞和到达时间不合适',
        '改签或退签因素',
        '经批准可不选择最低价航班',
        '其它'
      ];
      var str = reasonArr[that.data.item];
      that.jumpToOrderVc(that.data.flightInfo, that.data.cabinInfo, str, true, 1);
    }
  },
  //选择最低价航班
  chooseTheLessFlight: function () {
    console.log('选择最低价航班');
    var that = this;
    that.jumpToOrderVc(that.data.minFlightInfo, that.data.minCabinInfo, '', false, 0);
  },
  //订_action
  orderTap: function (event) {
    var that = this;


    //order tap
    app.globalData.fromCity = that.data.fromCity;
    app.globalData.toCity = that.data.toCity;
    var cellindex = event.currentTarget.dataset.cellindex;
    var index = event.currentTarget.dataset.index;
    console.log('cellIndex' + cellindex + ';' + 'index:' + index);
    var flightInfo = that.data.listArray[cellindex];
    var cabinInfo = flightInfo.Cabins[index];
    that.data.flightInfo = flightInfo;
    that.data.cabinInfo = cabinInfo;
    // //差标判断..
    if (that.data.trainStandard != null) {
      //是否可以购买保险
      var BuyInsuranceFlag = that.data.trainStandard.BuyInsuranceFlag;
      //是否可以购买头等舱、公务舱
      var BuyFirstClassFlag = that.data.trainStandard.BuyFirstClassFlag;
      //低价提醒标示
      var MinPriceRemindFlag = that.data.trainStandard.MinPriceRemindFlag;
      //指定时间内有更低价格机票提醒
      var MinPriceRemindTime = that.data.trainStandard.MinPriceRemindTime;
      console.log('差标判断');
      console.log(MinPriceRemindFlag, MinPriceRemindTime);

      //超标提醒
      if (BuyFirstClassFlag == false) {//不可以的时候判断是否选择了。(根据仓位Discount字段判断)
        if (cabinInfo.CabinName.indexOf('经济') >= 0) {//经济舱
          console.log('没超标.....');
        } else {
          console.log('超标了.....');
          that.setData({
            isShowAlert: true,
          })
          return;
        }
      }

      //最低价提醒
      if (MinPriceRemindFlag == true) {
        console.log('机票最小价提醒true');
        var nowA = flightInfo.OffTime.split(':');
        var nowD = nowA[0] * 60 + nowA[1] * 1;
        var beforeD = nowD - MinPriceRemindTime * 60;
        var afterD = nowD - 0 + MinPriceRemindTime * 60;
        console.log(nowA, nowD, beforeD, afterD);

        var nowDate = flightInfo.OffTime;
        var before = util.getTheDateBeforeOrAfter(nowDate, MinPriceRemindTime, true);
        var after = util.getTheDateBeforeOrAfter(nowDate, MinPriceRemindTime, false);
        var listArray = that.data.listArray;
        //筛选出最小航班仓位


        //判断是否有小于
        var min = listArray[0];
        for (var i = 1; i < listArray.length; i++) {
          var nowTimeArr = listArray[i].OffTime.split(':');
          var nowTime = nowTimeArr[0] * 60 + nowTimeArr[1] * 1;
          // console.log(nowTime,beforeD,afterD);
          if (nowTime >= beforeD && nowTime <= afterD) {
            // console.log(nowTime, beforeD, afterD);
            //筛选最低价航班
            if (listArray[i].MinFare - 0 < min.MinFare - 0) {
              min = listArray[i];
            }
          }
        }
        var minCabinInfo = min.Cabins[0];

        console.log(min.MinFare, minCabinInfo);
        if (min.MinFare < cabinInfo.Fare) {

          that.setData({
            isShowAlertLess: true,
            minFlightInfo: min,
            minCabinInfo: minCabinInfo,
          })
          return;
        }
      }
    }
    //跳转预定
    that.jumpToOrderVc(flightInfo, cabinInfo, '', false, 0);
  },
  //跳转到预定页
  /**
   * reasonStr:差标原因
   * IsOverStandard:是否超标
   * OverStandardType:超标类型（对应枚举OverStandardType：存在最未选择最低价航班= 1,舱位超标 = 2,坐席超标 = 3,）
   */
  jumpToOrderVc: function (flightInfo, cabinInfo, reasonStr, IsOverStandard, OverStandardType) {
    var that = this;
    wx.navigateTo({
      url: '../../flight/order/order?flightInfo=' + JSON.stringify(flightInfo) + '&cabinInfo=' + JSON.stringify(cabinInfo) + '&SerFee=' + that.data.SerFee + '&reasonStr=' + reasonStr + '&IsOverStandard=' + IsOverStandard + '&OverStandardType=' + OverStandardType
    })
  }

})